package com.lixiaoyi.emp.service.impl;

import com.lixiaoyi.emp.dao.IEmpDao;
import com.lixiaoyi.emp.dao.impl.EmpDaoImpl;
import com.lixiaoyi.emp.entity.Emp;
import com.lixiaoyi.emp.entity.Page;
import com.lixiaoyi.emp.service.IEmpService;
import com.lixiaoyi.emp.utils.DbUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author 李小毅
 * @Description
 * @Date 2022-05-12
 */

public class EmpServiceImpl implements IEmpService {

    private IEmpDao empDao = new EmpDaoImpl();
    @Override
    public List<Emp> showAllEmp() {

        //1。创建返回对象
        List<Emp> emps = new ArrayList<>();

        try {
            DbUtils.begin();
            List<Emp> temps = empDao.selectAll();
            if (temps!=null){
                emps = temps;
            }
            DbUtils.commit();
        } catch (Exception e) {
            DbUtils.rollback();
            e.printStackTrace();
        }
        return emps;
    }

    @Override
    public int removeEmp(int id) {
        int result = 0;
        try {
            DbUtils.begin();
            result = empDao.delete(id);
            DbUtils.commit();
        } catch (Exception e) {
            DbUtils.rollback();
            e.printStackTrace();
        }

        return result;
    }

    @Override
    public int modify(Emp emp) {
        int result = 0;
        try {
            DbUtils.begin();
            result = empDao.update(emp);
            DbUtils.commit();
        } catch (Exception e) {
            DbUtils.rollback();
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public Emp showEmp(int id) {
        Emp emp = null;
        try {
            DbUtils.begin();
            emp = empDao.select(id);
            DbUtils.commit();
        } catch (Exception e) {
            DbUtils.rollback();
            e.printStackTrace();
        }

        return emp;
    }

    @Override
    public Emp add() {
        Emp emp = null;

        try {
            DbUtils.begin();
            empDao.add();
            DbUtils.commit();
        } catch (Exception e) {
            DbUtils.rollback();
            e.printStackTrace();
        }

        return emp;
    }

    @Override
    public List<Emp> showAllEmp(Page page) {

        List<Emp> emps = null;
        try {
            DbUtils.begin();
            long count = empDao.selectCount();
            page.setTotalCounts((int)count);
            emps = empDao.selectByPage(page);
            DbUtils.commit();
        } catch (Exception e) {
            DbUtils.rollback();
            e.printStackTrace();
        }
        return emps;
    }
}
